$(document).ready(function () {
    class MiniCart {
        constructor() {}
        static setAllCount() {
            $('.shop_count').text($('#header .shoppingCartArea ul li').length)
            $('.minicart .cartNum').text($('#header .shoppingCartArea ul li').length)
        }
        static removeItem(index) {
            let $item = $(`.shop_item[data-index=${index}]`);
            $item.remove();
            Goods.remove(index);
        }
        static setAllTotal(allTotal = Goods.locale(Goods.countAllTotal())) {
            $('.allTotal').text(allTotal)
        }
        static renderCart(data) {
            $('.shop_no').hide();
            $('.shop_have').show();
            $('.shop_total').show();
            let str = "";
            data.forEach((item, index) => {
                let goods = new Goods(index, item);
                str += `<li class="shop_item" data-index="${index}">
                <img src="/img/${goods.cover}">
                <div class="name">${goods.name}</div>
                <div class="qty">X${goods.num}</div>
                <div class="price">RMB
                    <span>${Goods.locale(goods.total)}</span></div>
                <div><a rel="nofollow" href="javascript:" class="delete cp_del">删除</a></div>
            </li>`
            });
            $('.minicart ul').html(str);
        }
    }
    window.loadCart = function() {
        if (!sessionStorage.uid) {
            return;
        }
        $.ajax({
            type: "post",
            url: "/searchCart",
            data: {
                uid: sessionStorage.uid
            },
        }).done(function (res) {
            let data = res.data;
            MiniCart.renderCart(data);
            MiniCart.setAllTotal();
            MiniCart.setAllCount();
            $('.minicart').on('click', '.cp_del', function () {
                MiniCart.removeItem(this.closest('.shop_item').dataset.index)
                MiniCart.setAllTotal();
                MiniCart.setAllCount();
            })
        });
    }
    window.loadCart();
})